﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;
using System.Net;

namespace ReserveMeWCFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class ReserveService : IReserveService
    {
        private const String clientDirectory = @"/clients/xml/";
        
       public void update(Stream stream, String clientID, string FileName)
       {
           if (WebOperationContext.Current.IncomingRequest.Headers["Stream"] != "GZip")
           {
               throw new WebFaultException<string>("Invalid Request", HttpStatusCode.BadRequest);
           }
           else
           {
               FileStream targetStream = null;
               Stream source = stream;
               string filename = clientID.ToString();
               string filePath = Path.Combine(clientDirectory,filename);
               string pathAndFile = Path.Combine(filePath, FileName);
               
               if (!File.Exists(filePath))
               {
                   Directory.CreateDirectory(filePath);
               }

               using(targetStream = new FileStream(pathAndFile, FileMode.Create, FileAccess.Write, FileShare.None))
               {
                   const int buffsize = 4096;
                   byte[] buffer = new byte[buffsize];
                   int count = 0;    
                   while((count = source.Read(buffer, 0, buffsize)) > 0)
                   {
                       targetStream.Write(buffer, 0, count);
                   }
                   targetStream.Close();
                   source.Close();
               }
           }    
       }
    }
}
